<template>
  <div class="container">
    <header>
      <div>
        <img src="../assets/back.svg" alt="" @click="goBack">
        <span>确认订单</span>
        <div>
          <img src="../assets/time.svg" alt="">
          <van-count-down :time="time" />
        </div>
      </div>
    </header>
    <div class="wrap">
      <div class="wrap-con">
        <div class="card">
          <div>
            <img :src="$buildFullImageUrl + filmData.pic" alt="">
            <div>
              <div>
                <div>
                  <div>{{ showData.film_name }}</div>
                  <div>{{ seatesPrice.length }}张</div>
                </div>
                <div>原价 ¥ {{ $route.query.totalPrice }}</div>
              </div>
              <div>
                {{ formatShowTime(showData) }} {{ showData.version_type }}
              </div>
              <div>{{ showData.cinema_name }}</div>
              <div>{{ showData.hall_name }}</div>
            </div>
          </div>
        </div>
        <div class="hasSelect">
          <div class="hasSelectSeats" v-for="(item, index) in seatesPrice" :key="index">
            <div class="seat_names">
              <div>{{ item.seat_name }}</div>
              <div> {{ item.price }}</div>
            </div>
          </div>
        </div>
        <div class="sel-card">
          <div v-for="(item, index) in cardList" :key="index">
            <div class="sel-card-con" v-if="item.cardMode == 1" style="margin-top: 20px">
              <div>
                <img src="../assets/mine/card.svg" alt="">
                <div class="con">
                  <div>
                    <span>职工观影兑换卡</span>
                    <span>剩余{{ item.balance }}次</span>
                  </div>
                  <div>
                    <span>有效期至</span>
                    <span>{{ item.validEndDate }}</span>
                  </div>
                </div>
              </div>
              <van-checkbox :value="isCardSelected(item.id)" @click="selectPayment('card', item.cardMode, item)">
              </van-checkbox>
            </div>
            <div class="sel-card-con" style="margin-top: 20px" v-if="item.cardMode == 2">
              <div>
                <img src="../assets/mine/card.svg" alt="">
                <div class="con">
                  <div>
                    <span>积分</span>
                    <span>剩余{{ item.balance }}积分</span>
                  </div>
                  <div>
                    <span>有效期至</span>
                    <span>{{ item.validEndDate }}</span>
                  </div>
                </div>
              </div>
              <van-checkbox :value="isCardSelected(item.id)" @click="selectPayment('points', item.cardMode, item)">
              </van-checkbox>
            </div>
          </div>
        </div>
      </div>
      <div class="know">
        <div>兑换须知</div>
        <div>
          <div>1.请确认场次和时间无误,购买成功后将不予退换</div>
          <div>2.由于设备故障等不可抗力因素,存在少量场次取消的情况,会进行退票退款 </div>
          <div>3.由于影院系统不稳定等因素,存在出票失败的情况,会进行退款</div>
          <div>4.取票码可以在“我的-电影票”中查看</div>
          <div>
            5.下单即代表你同意
            <span style="color: #42a5f5">《用户服务协议》</span>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom-btn">
      <div>{{ totalPay }}</div>
      <div>
        <div @click="payDetail">
          <span>明细</span>
          <img src="../assets/order/topset.svg" alt="">
        </div>
        <div @click="nowBuy">
          立即兑换
        </div>
      </div>
    </div>
    <van-popup v-model="show" position="bottom">
      <div class="dialog_data">
        <div class="title">价格明细</div>
        <div v-for="(item, index) in seatDeductions" :key="index" class="detailList">
          <div>
            <div>
              座位号：{{ item.seat_name }}
            </div>
            <div style="margin-top: 5px;">
              原价：{{ item.seatPrice }}
            </div>
          </div>
          <div>
            <div>
              抵扣积分：{{ item.deduction }}
            </div>
            <div style="margin-top: 5px;">
              抵扣钱数：{{ item.paid || 0 }}
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { Toast } from 'vant';
import plantAPI from "@/api/plant";
export default {
  data() {
    return {
      show: false,
      seatDeductions: [],
      totalPay: '',
      selectedCardMode: null,
      selectedCards: [],
      time: 10 * 60 * 1000,
      selectedPayment: '', // 'card' 或 'points'
      showData: {},
      filmData: {},
      seatesPrice: [],
      cardList: [],
      hasEnoughPointsCard: false,
      originalPrice: 0
    }
  },
  created() {
    this.showData = JSON.parse(this.$route.query.showData)
    this.filmData = JSON.parse(this.$route.query.filmData)
    this.seatesPrice = JSON.parse(this.$route.query.seatesPrice)
    this.originalPrice = parseFloat(this.$route.query.totalPrice) || 0
    plantAPI.cardList().then(res => {
      this.cardList = res.rows
    })
    // setTimeout(() => {
    //   this.$router.push({
    //     path: '/user'
    //   })
    // }, 600000)
  },
  computed: {
    selectedCardTypes() {
      if (this.selectedCards.length === 0) return [];
      const modes = new Set();
      this.cardList.forEach(card => {
        if (this.selectedCards.includes(card.id)) {
          modes.add(card.cardMode);
        }
      });
      return Array.from(modes);
    },
    totalSelectedPoints() {
      if (this.selectedCardMode !== 2) return 0;
      return this.selectedCards.reduce((total, cardId) => {
        const card = this.cardList.find(c => c.id === cardId);
        return total + (card ? card.balance : 0);
      }, 0);
    },
    isPointsEnough() {
      return this.totalSelectedPoints >= this.originalPrice;
    },
    isFirstCardEnough() {
      if (this.selectedCards.length === 0 || this.selectedCardMode !== 2) return false;
      const firstCard = this.cardList.find(c => c.id === this.selectedCards[0]);
      return firstCard && firstCard.balance >= this.originalPrice;
    }
  },
  methods: {
    payDetail() {
      this.show = true
      const seatMap = new Map(this.seatesPrice.map(item => [item.seatId, item.seat_name]));
      this.seatDeductions.forEach(item => {
        if (seatMap.has(item.seatId)) {
          item.seat_name = seatMap.get(item.seatId);
        }
      });

    },
    goBack() {
      this.$router.back()
    },
    selectPayment(type, cardMode, item) {
      if (this.selectedCardMode && this.selectedCardMode !== cardMode) {
        this.$toast(`请勿选择不同类型的卡`);
        return;
      }
      const index = this.selectedCards.indexOf(item.id);

      if (cardMode == 1) {
        if (index === -1) {
          this.selectedCards = [item.id];
          this.selectedCardMode = cardMode;
        } else {
          this.selectedCards = [];
          this.selectedCardMode = null;
        }
      } else {
        if (index === -1) {
          if (this.hasEnoughPointsCard) {
            this.$toast('当前积分卡已足够支付，无需选择更多');
            return;
          }
          this.selectedCards.push(item.id);
          this.selectedCardMode = cardMode;
          const selectedCard = this.cardList.find(c => c.id === item.id);
          if (selectedCard && selectedCard.balance >= this.originalPrice) {
            this.hasEnoughPointsCard = true;
          }
        } else {
          // 取消选中
          this.selectedCards.splice(index, 1);
          if (this.selectedCards.length === 0) {
            this.selectedCardMode = null;
            this.hasEnoughPointsCard = false;
          } else {
            // 检查剩余卡是否足够
            const total = this.selectedCards.reduce((sum, id) => {
              const card = this.cardList.find(c => c.id === id);
              return sum + (card ? card.balance : 0);
            }, 0);
            this.hasEnoughPointsCard = total >= this.originalPrice;
          }
        }
      }
    },
    nowBuy() {
      if (this.selectedCardMode === null) {
        this.$toast('请选择支付方式');
        return;
      }
      const seatInfo = this.seatesPrice.map(seat => ({
        seatId: seat.seat_id,
        seatPrice: seat.price
      }));

      plantAPI.getAdditionalAmount({
        cardIds: this.selectedCards,
        seatInfoList: seatInfo,
        cardMode: this.selectedCardTypes[0]
      }).then(res => {
        this.totalPay = res.data.totalPay;
        // 支付详情
        this.seatDeductions = res.data.seatDeductions
      }).catch(error => {
      });
    },
    isCardSelected(id) {
      return this.selectedCards.includes(id);
    },
    formatShowTime(showData) {
      if (!showData || !showData.show_date || !showData.show_time || !showData.close_time) {
        return '';
      }
      // 解析日期
      const showDate = new Date(showData.show_date);
      const showTime = new Date(showData.show_time);
      const closeTime = new Date(showData.close_time);
      // 获取今天的日期
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      // 计算日期差
      const diffDays = Math.floor((showDate - today) / (1000 * 60 * 60 * 24));
      // 确定日期显示文本
      let dateText = '';
      if (diffDays === 0) {
        dateText = '今天';
      } else if (diffDays === 1) {
        dateText = '明天';
      } else if (diffDays === 2) {
        dateText = '后天';
      } else {
        const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        dateText = weekDays[showDate.getDay()];
      }
      // 获取月份和日期
      const month = showDate.getMonth() + 1;
      const day = showDate.getDate();
      // 获取小时和分钟
      const startHours = showTime.getHours().toString().padStart(2, '0');
      const startMinutes = showTime.getMinutes().toString().padStart(2, '0');
      const endHours = closeTime.getHours().toString().padStart(2, '0');
      const endMinutes = closeTime.getMinutes().toString().padStart(2, '0');

      return `${dateText} ${month}月${day}日 ${startHours}:${startMinutes}-${endHours}:${endMinutes}`;
    },
  }
}
</script>
<style lang="scss" scoped>
::v-deep .van-count-down {
  color: #fff !important;
}

.dialog_data {
  color: #999;
  font-size: 14px;
  background: #eee;
  text-align: center;
  padding: 20px 0;

  .detailList {
    width: 320px;
    margin: auto;
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 6px;
    margin-top: 10px;
    padding: 10px 20px;

    >div {
      margin-top: 5px;
      width: 50%;
      text-align: left;
    }
  }

  .title {
    color: #000;
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
  }
}

.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: rgba(245, 245, 245, 1);
  position: relative;
  overflow: hidden;

  header {
    width: 100%;
    height: 139px;
    background: linear-gradient(94deg, rgba(238, 71, 59, 0.05) 0%, #f6766d 58%, rgba(238, 71, 59, 0.3) 100%);
    opacity: 0.8;
    position: relative;

    >div {
      width: 100%;
      padding: 20px 16px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: relative;

      >img:first-child {
        width: 20px;
        height: 20px;
        flex-shrink: 0;
      }

      >span {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        color: rgb(255, 255, 255);
        font-size: 17px;
      }

      >div:last-child {
        display: flex;
        align-items: center;
        flex-shrink: 0;

        img {
          width: 16px;
          height: 16px;
        }

        .van-count-down {
          color: #fff !important;
          font-size: 14px;
          margin-left: 5px;
        }
      }
    }
  }

  .bottom-btn {
    width: 100%;
    position: sticky;
    bottom: 0;
    z-index: 100;
    height: 61px;
    background: #FFFFFF;
    display: flex;
    padding: 0 17px;
    box-sizing: border-box;
    justify-content: space-between;
    align-items: center;

    >div:nth-child(1) {
      color: rgba(251, 55, 119, 1);
      font-size: 16px;
      font-weight: bold;
    }

    >div:nth-child(2) {
      display: flex;
      align-items: center;

      >div:nth-child(1) {
        color: rgba(186, 186, 186, 1);
        font-size: 12px;
        display: flex;
        align-items: center;

        img {
          width: 10px;
          height: 10px;
          margin-left: 5px;
        }
      }

      >div:nth-child(2) {
        margin-left: 18px;
        border-radius: 20px;
        width: 160px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        color: rgba(255, 255, 255, 1);
        font-size: 16px;
        background-color: rgba(251, 55, 119, 1);
      }
    }
  }

  .wrap {
    z-index: 111;
    flex: 1;
    /* 占据剩余空间 */
    overflow-y: auto;
    /* 启用纵向滚动 */
    padding: 0 13px;
    padding-bottom: 20px;
    /* 给底部按钮留出空间 */
    margin-top: -70px;
    /* 保持与header的重叠效果 */
    -webkit-overflow-scrolling: touch;
    /* iOS平滑滚动 */

    .wrap-con {
      width: 100%;
      background: #FFFFFF;
      border-radius: 8px;
      margin-bottom: 10px;
    }

    .card {
      width: 100%;
      padding: 0 10px;
      box-sizing: border-box;

      >div:nth-child(1) {
        width: 100%;
        padding: 20px 0 30px 0;
        display: flex;

        >img:nth-child(1) {
          width: 78px;
          height: 100px;
          border-radius: 4px;
        }

        >div:nth-child(2) {
          width: calc(100% - 81px);
          margin-left: 10px;

          >div:nth-child(1) {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;

            >div:nth-child(1) {
              display: flex;
              align-items: center;

              >div:nth-child(1) {
                width: 125px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                color: rgb(16, 16, 16);
                font-size: 16px;
                font-weight: bold;
                margin-right: 5px;
              }

              >div:nth-child(2) {
                color: rgb(51, 51, 51);
                font-size: 14px;
              }
            }

            >div:nth-child(2) {
              color: rgba(51, 51, 51, 1);
              font-size: 14px;
            }
          }

          >div:nth-child(2),
          >div:nth-child(3),
          >div:nth-child(4) {
            font-size: 12px;
            text-align: left;
            color: rgba(102, 102, 102, 1);
            margin-top: 5px;
          }
        }
      }
    }

    .hasSelect {
      display: flex;
      align-items: center;
      margin-left: 6px;
      overflow-x: auto;
      /* 添加横向滚动 */
      white-space: nowrap;
      /* 防止子元素换行 */
      // padding-bottom: 10px;
      /* 为滚动条留出空间 */
      -webkit-overflow-scrolling: touch;
      /* iOS平滑滚动 */

      .hasSelectSeats {
        display: inline-flex;
        /* 改为行内flex布局 */
        align-items: center;
        padding: 0 10px;
        height: 46px;
        background: #F6F6F6;
        border-radius: 6px;
        margin-right: 8px;
        flex-shrink: 0;
        /* 防止元素被压缩 */
        cursor: pointer;
      }

      .line {
        width: 0px;
        height: 32px;
        border: 0.5px solid #D1D1D1;
        margin: 0 5px;
      }

      .seat_names {
        text-align: center;
        padding-right: 10px;

        >div:first-child {
          height: 18px;
          font-family: PingFang SC;
          font-weight: 500;
          font-size: 13px;
          color: #1A1A1A;
        }

        >div:last-child {
          height: 17px;
          font-family: PingFang SC;
          font-weight: 400;
          font-size: 12px;
          color: #1A1A1A;
        }
      }
    }

    .sel-card {
      width: calc(100% - 30px);
      padding: 0px 10px 20px 10px;
      box-sizing: border-box;
      margin: auto;

      .sel-card-con {
        width: 100%;
        display: flex;
        justify-content: space-between;

        >div:nth-child(1) {
          width: calc(100% - 25px);
          display: flex;
          align-items: center;

          img {
            width: 24px;
            height: 24px;
          }

          .con {
            margin-left: 13px;

            >div:nth-child(1) {
              display: flex;
              align-items: center;

              span:nth-child(1) {
                color: rgb(16, 16, 16);
                font-size: 14px;
              }

              span:nth-child(2) {
                color: rgb(186, 186, 186);
                font-size: 14px;
                margin-left: 27px;
              }
            }

            >div:nth-child(2) {
              display: flex;
              align-items: center;

              span:nth-child(1) {
                color: rgb(186, 186, 186);
                font-size: 14px;
              }

              span:nth-child(2) {
                color: #72b311;
                font-size: 14px;
                margin-left: 10px;
              }
            }
          }
        }

      }
    }

    .know {
      width: calc(100% - 30px);
      margin: 10px auto 0;
      border-top: 1px solid rgba(206, 206, 206, 1);

      >div:nth-child(1) {
        width: 100%;
        color: rgb(51, 51, 51);
        font-size: 14px;
        text-align: left;
        font-weight: bold;
        margin-top: 10px;
      }

      >div:nth-child(2) {
        width: 100%;
        margin-top: 29px;

        >div {
          color: rgba(102, 102, 102, 1);
          font-size: 13px;
          text-align: left;
          margin-bottom: 10px;
        }
      }
    }
  }
}
</style>